<template>
  <div>
    <el-upload :action="`${$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/smis`"
      :multiple="limit==1?false: true"
      :headers="{token: $cookie.get('token')}" :accept="accept" :limit="limit" list-type='picture-card'
      :before-upload="checkMeasure" :on-success="(response, file, fileList) => {
        // filePath = (file.response && file.response.url) || file.url
        filePath = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
				$emit('onNameChange', file.name)
      }" :on-progress="onProgress" :on-exceed="(files, fileList)=> {
        $message.warning(`只允许上传选择 ${limit} 个文件`)
      }" :on-remove="(file, fileList) => {
        // $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
        //  $message.success(data.msg)
        // })
        // filePath = ''
        filePath = fileList.map(item => item.url).join('|')
      }" :file-list="files">
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <div v-if="!file.response && file.url.startsWith('blob:')" style="height: auto; text-align: center;"
          class="el-upload-list__item-thumbnail uni-center-xy">{{percent === '100%' ? '处理中...': '上传中'+percent+'...'}}
        </div>
        <video v-else-if="file.name.endsWith('.mp4')" class="el-upload-list__item-thumbnail uni-center-xy"
          :src="file.url">
          您的浏览器不支持 video 标签。
        </video>
        <img style="height: auto;" v-else-if="file.name.endsWith('.JPG') || file.name.endsWith('.png') || file.name.endsWith('.jpg') || file.name.endsWith('.jpeg')" class="el-upload-list__item-thumbnail uni-center-xy" :src="file.url" alt="file.name">
        <div v-else style="height: auto; line-height: 1.8; background-color: #CCCCCC; text-align: center;"
          class="el-upload-list__item-thumbnail uni-center-xy" alt="file.name">
          {{file.name}}
        </div>

        <img src="../../assets/img/video.png" class="uni-center-xy" style="width: 40px; z-index: 0;"
          v-if="!(!file.response && file.url.startsWith('blob:')) && file.name.endsWith('.mp4')">
        <span class="el-upload-list__item-actions">
          <!-- <span class="el-upload-list__item-preview"  @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span> -->
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <!-- <el-button size="small" type="primary">点击上传</el-button> -->
      <div slot="tip" class="el-upload__tip">只能上传{{accept}}格式文件<span
          v-if="fileType === '2'">，图片尺寸要求：{{width}}*{{height}}</span></div>
    </el-upload>
  </div>
</template>
<script>
  import { scale } from '../../utils/scale.js' // 图片压缩方法
  export default {
    name: "vrUploadExt",
    data() {
      return {
        filePath: "",
        files: [],
        errList: [],
        percent: '',
        dialogVisible: false,
        // 防止重复提交
        loading: false,
        _name: ""
      };
    },
    props: {
      limit: {
        type: Number,
        default: 1
      },
      disabled: {
        type: Boolean,
        default: false
      },
      accept: {
        type: String,
        default: () => {
          return null
        }
      },
      fileType: {
        type: String,
        default: () => {
          return null
        }
      },
      width: {
        type: String,
        default: () => {
          return '2048'
        }
      },
      height: {
        type: String,
        default: () => {
          return '1024'
        }
      },
      outputSize: {
        // 裁剪生成图片的质量 0.0~1.0
        type: Number,
        default: 0.7
      },
      outputType: {
        type: String,
        default: 'jpg', // 裁剪生成图片的格式
      },
      allowScale: {
        // 是否允许同比例的
        type: Boolean,
        default: true
      },
      allowOtherSize: {
        // 是否允许其他尺寸
        type: Boolean,
        default: false
      },
      maxImageSize: {
        // 是否允许其他尺寸
        type: Number,
        default: 6 * 1024 * 1024
      },
      value: {
        type: String,
        default: () => {
          return null
        }
      },
      directUpload: {
        // 检查数据库中jf_vr_list表，通过判断name是否和file的name一致，一致且该条数据照片为空，则执行插入图片操作,直接更新数据库数据
        type: Boolean,
        default: false
      },
      cameraCode: {
        type: String,
        default: ''
      },
      name: {
        type: String,
        default: () => {
          return ""
        }
      }
    },
    // components: {
    //   VueCropper,
    // },
    computed: {
      // files: {
      //   get () {
      //     if (!this.filePath) {
      //       return []
      //     }
      //     var arr = []
      //     var list = this.filePath.split("|");
      //     list.forEach((path)=>{
      //       var obj= path.lastIndexOf("/")
      //       var fileName = path.substr(obj+1)
      //       arr.push({name: fileName, url: path})
      //     })
      //     return arr
      //   }
      // }
    },
    watch: {
      value(val) {
        if (this.filePath !== val) {
          this.filePath = val
          this.computedFiles(val)
        }
      },
      filePath(val) {
        var _val = val || '';
        var urls = this.myTrim(_val, '|')
        this.$emit('input', urls)
        this.$emit('onChange', urls)
      }
    },
    methods: {
      myTrim(str, char) {
        return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
      },
      computedFiles(val) {
        this.files = []
        if (val) {
          var list = val.split("|");
          list.forEach((path) => {
            var obj = path.lastIndexOf("/")
            var fileName = path.substr(obj + 1)
            if (this.name && this.name !== "") {
              fileName = this.name
            }
            this.files.push({
              name: fileName,
              url: path
            })
          })
        }
      },
      onProgress(event, file, fileList) {
        this.percent = Math.floor(event.percent) + "%"
      },
      cropperLoad(data) {
        if (data === 'success') {
          var cropW = this.$refs.cropper.cropW
          var autoCropWidth = this.option.autoCropWidth
          this.option.enlarge = autoCropWidth * 1.0 / cropW
          // console.log("enlarge:"+this.option.enlarge)
        }
      },
      uploadVrData(result, fileName) {
        let file = new window.File([result], fileName, {
          type: 'image/png'
        })
        this.loading = true
        var formData = new FormData()
        formData.append('file', file)
        formData.append('cameraCode', this.cameraCode)
        this.$http({
          url: '/smis/vr/jfVrList/uploadVrData',
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(({
          data
        }) => {
          this.loading = false
          if (data && data.success) {
            this.dialogVisible = false
            if (this.filePath && this.filePath !== '') {
              this.filePath = this.filePath + '|' + data.url
            } else {
              this.filePath = data.url
            }
            this.$emit("onProgress", fileName);
            this.$emit("onNameChange", data.name)
            this.computedFiles(this.filePath)
          } else {
            this.errList.push(data.msg)
            this.$emit("onError", this.errList)
          }
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
      },
      // 点击裁剪，这一步是可以拿到处理后的地址
      finish(result) {
        // this.$refs.cropper.getCropData((data) => {
        //   let image = new Image()
        //   image.src = data
        //   image.onload = (e) => {
        //    console.log(image.width+','+image.height)
        //   }
        // })
        // return
          //上传到服务器
        let file = new window.File([result], '123.png', {
          type: 'image/png'
        })
        this.loading = true
        var formData = new FormData()
        formData.append('file', file)
        this.$http({
          url: '/sys/file/webupload/upload?uploadPath=/smis',
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(({
          data
        }) => {
          this.loading = false
          if (data && data.success) {
            this.dialogVisible = false
            if (this.filePath && this.filePath !== '') {
              this.filePath = this.filePath + '|' + data.url
            } else {
              this.filePath = data.url
            }
            this.$emit("onNameChange", data.name)
            this.computedFiles(this.filePath)
          }
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
      },
      _greater2G(file) {
        if (file.size > 2 * 1024 * 1024 * 1024) {
          this.$message.warning(`文件大小不能超过2G`)
          return true
        }
        return false
      },
      /**
       * 检查数据库中jf_vr_list表，通过判断name是否和file的name一致，一致且该条数据照片为空，则执行插入图片操作
       * @param {Object} file
       */
      checkVrServer(file) {
        // console.log(file)
        this.loading = true
        this.$http({
          url: `/smis/vr/jfVrList/getListByName?name=${file.name || ''}`,
          method: 'get'
        }).then(({data}) => {
          this.loading = false
          if (data && data.success) {
            if(data.list.length === 0) {
              console.log("不存在");
            } else if(data.list.length != 1) {
              console.log("存在"+data.list.length+"条记录");
            }
          }
        })
      },
      checkMeasure(file) {
        // if(this.checkServer) {
        //   this.checkVrServer(file)
        //   return false
        // }
        var fileName = file.name || ''
        if (this.files.length >= this.limit) {
          this.$message.warning(`只允许上传选择 ${this.limit} 个文件`)
          return false
        }
        if (file && file.type && !file.type.startsWith("image")) {
          // 非图片的内容
          if (this._greater2G(file)) {
            return false
          }
          return true
        }
        if (file && file.type && file.type.startsWith("image/gif")) {
          // 非图片的内容
          if (this._greater2G(file)) {
            return false
          }
          return true
        }
        if (this.fileType !== '2') {
          // 如果不是图片，则不检测长宽
          return true
        }
        if (!this.width || this.width === '') {
          // 不检测宽度
          return true
        }
        if (!this.height || this.height === '') {
          // 不检测高度
          return true
        }
        if (!this.height || this.height === '') {
          // 不检测高度
          return true
        }
        if (file.size > this.maxImageSize) {
          if (this.maxImageSize < 1024 * 1024) {
            this.$message.warning('图片大小不能超过' + Math.floor(this.maxImageSize / 1024) + 'k')
          } else {
            this.$message.warning('图片大小不能超过' + (this.maxImageSize / (1024 * 1024)).toFixed(1) + 'M')
          }

          return false
        }

        var width = parseInt(this.width)
        var height = parseInt(this.height)
        var that = this
        const isSize = new Promise((resolve, reject) => {
          let _URL = window.URL || window.webkitURL
          let image = new Image()
          image.onload = (e) => {
            // console.log(e)
            if (that.allowScale && (image.width * 1.0 / image.height).toFixed(2) === (width * 1.0 / height)
              .toFixed(2)) {
              resolve()
            } else if (!that.allowScale && image.width === width && image.height === height) {
              resolve()
            } else if (that.allowOtherSize) {
              that.$confirm('图片尺寸' + image.width + '*' + image.height + '，不符合要求的尺寸' + width + '*' + height +
                ', 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                resolve()
              }).catch(() => {
                reject()
              })
            } else {
              reject()
              // var jpegImage  = scale({width:2048, height:1024}, img, 'jpeg');
              let config = {
                width: parseInt(that.width), // 压缩后图片的宽
                height: parseInt(that.height), // 压缩后图片的高
                quality: parseFloat(that.outputSize) // 压缩后图片的清晰度，取值0-1，值越小，所绘制出的图像越模糊
              }

              var jpegImage  = scale(config, image, that.outputType);
              let fileBinary = that.dataURLtoBlob(jpegImage.src)
              if(that.directUpload) {
                that.uploadVrData(fileBinary, fileName)
              } else {
                that.finish(fileBinary, fileName)
              }
              // compressImage(file, config)
              //   .then(result => { // result 为压缩后二进制文件
              //     that.finish(result)
              //   })
            }
          }
          image.src = _URL.createObjectURL(file)
        }).then(
          () => { // resolve
            return file;
          },
          () => { // 取消上传 reject
            return Promise.reject();
          }
        )
        return isSize
      },
      handleRemove(file) {
        this.files = this.files.filter((item) => {
          return item.uid !== file.uid
        })
        this.filePath = this.files.map(item => item.url).join('|')
      },
      handlePictureCardPreview(file) {
        // this.dialogImageUrl = file.url;
        // this.dialogVisible = true;
      },
      handleDownload(file) {
        window.location = file.url;
        // console.log(file);
      },
      // 将base64转为二进制
      dataURLtoBlob (dataurl) {
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
      }
    }
  };
</script>
<style scoped="scoped">
  .cropper-content .cropper {
    width: 100%;
    height: 300px;
  }
</style>
